<template>
  <div class="app-container bg">
    <div class="box-container">
      <div
        class="mb15"
        style="border-bottom: 1px solid #ddd; margin-bottom: 10px"
      >
        <el-radio-group
          v-model="showType"
          @change="showTypeChange"
          style="gap: 40px"
        >
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2">学员</el-radio-button>
        </el-radio-group>
      </div>

      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="
          font-size: 14px;
          line-height: 25px;
          margin-top: 20px;
          cursor: pointer;
          border-bottom: 1px solid #ddd;
        "
      >
        <!-- <el-col :span="2.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ registerBaseVo.total || 0 }}
          </div>
        </el-col>
        <el-col :span="3.5">
          <div
            @click="clickAll(1, 1)"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            全勤人数：{{ registerBaseVo.leaveStatus1 || 0 }}
          </div>
        </el-col> -->
        <el-col :span="3.5">
          <div
            @click="clickAll(2, 2)"
            class="nactive"
            :class="{ active: tagIndex == 2 }"
          >
            请假人数：{{ registerBaseVo.leaveStatus2 || 0 }}
          </div>
        </el-col>
      </el-row>

      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="leaveOpen">考勤状态调整</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="logOpen"
            >考勤调整记录</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="handleLeave"
            >请假</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label=""
        style="width: 160px"
        prop="registerTypeId"
        v-if="false"
      >
        <el-select
          v-model="queryParams.registerTypeId"
          placeholder="请选择招生类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerTypeList"
            :key="index"
            :label="item.registerTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          format="yyyy"
          style="width: 160px"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.total }}
              <div class="desc">录取总数</div>
            </div>

            <div class="col">
              <span class="red">{{ row.leaveStatus2 }}</span>
              <div class="desc">请假人数</div>
            </div>
            <div class="col">
              {{ row.leaveStatus1 }}
              <div class="desc">全勤人数</div>
            </div>
            <div class="col">
              {{ row.cultureStatus3 }}
              <div class="desc">已结业</div>
            </div>
          </div>
          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <div v-if="showType == 2" class="custom-table">
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="border" style="display: flex; flex: 8">
            <div>
              <div class="user-name">
                <div style="margin-right: 10px">
                  <el-checkbox
                    v-model="row.check"
                    style="transform: scale(1.2)"
                    @change="handleSelectionChange($event, index)"
                  />
                </div>
                <span
                  @click="detailOpenInfo(row)"
                  style="
                    font-size: 18px;
                    font-weight: bolder;
                    color: #a52529;
                    cursor: pointer;
                  "
                  >{{ row.userName }}</span
                >
                <!-- <el-tag
                  type="success"
                  color="#fff"
                  style="
                    margin-left: 10px;
                    color: #f5a623;
                    border: 1px solid #f5a623;
                  "
                  >{{ row.currentStatusName }}</el-tag
                > -->

                <div style="margin-left: auto; font-size: 12px; color: #999">
                  工号：{{ row.jobNumber }}
                </div>
              </div>
              <div class="info">
                <div class="flexInfo">
                  <div>进修科目：{{ row.registerDeptName }}</div>
                  <div>
                    请假次数：{{ (row.registerLeaveVoList || []).length }}次
                  </div>
                  <div style="display: flex">
                    请假前进修期限：
                    <span v-if="row.registerNoticeVo"
                      >{{ row.registerNoticeVo.startDate }} -
                      {{ row.registerNoticeVo.endDateDefault
                      }}{{
                        getDayDiff(
                          row.registerNoticeVo.startDate,
                          row.registerNoticeVo.endDateDefault
                        )
                      }}</span
                    >
                  </div>
                </div>
                <div class="flexInfo">
                  <div style="display: flex; align-items: center">
                    请假天数：
                    {{ row.leaveDuration }}
                  </div>
                  <div style="display: flex; align-items: center">
                    销假天数：
                    {{ (row.leaveStat || {}).closeDays || 0 }}
                  </div>
                  <div style="display: flex; align-items: center">
                    请假后进修时间：<span v-if="row.registerNoticeVo"
                      >{{ row.registerNoticeVo.startDate }} -
                      {{ row.registerNoticeVo.endDate }}</span
                    >
                    <div v-if="row.leaveStatusDesc" style="color: #a52529">
                      （{{ row.leaveStatusDesc }}）
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div
            class="border"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="leaveOpen(row)"
              >请假
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="closeLevelOpen(row)"
              v-if="(row.registerLeaveVoList || []).length > 0"
              >销假
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="detailOpen(row)"
              >查看详情
            </el-button>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="请假"
      :visible.sync="leaveShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="leaveForm"
        :model="leaveForm"
        :rules="leaveRules"
        label-width="100px"
      >
        <el-form-item label="学员姓名" prop="registerId">
          <div>{{ leaveForm.userName }}</div>
        </el-form-item>
        <el-form-item label="请假总时长">
          <div>{{ leaveForm.totalLeaveDuration || 0 }}天</div>
        </el-form-item>
        <!-- <el-form-item label="请假状态" prop="leaveStatus">
          <el-radio-group v-model="leaveForm.leaveStatus">
            <el-radio
              v-for="(item, index) in leaveStatusList"
              :key="index"
              :label="item.id"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <div v-if="leaveForm.leaveStatus == 2">
          <div
            v-for="(item, index) in leaveForm.leaveItems"
            :key="index"
            style="
              position: relative;
              border: 1px solid #ebeef5;
              border-radius: 4px;
              padding: 25px 15px 15px 15px;
              margin-bottom: 15px;
            "
          >
            <div style="position: absolute; top: 5px; right: 5px">
              <i
                v-if="index === 0 || (index > 0 && index < 4)"
                class="el-icon-circle-plus"
                style="
                  margin-right: 5px;
                  cursor: pointer;
                  color: #a52529;
                  font-size: 24px;
                "
                @click="addLeaveItem"
              ></i>
              <i
                v-if="index > 0"
                class="el-icon-remove"
                style="cursor: pointer; color: #a52529; font-size: 24px"
                @click="removeLeaveItem(index)"
              ></i>
            </div>

            <el-form-item
              :label="'请假类型'"
              :prop="'leaveItems.' + index + '.leaveType'"
              :rules="leaveRules.leaveType"
            >
              <el-radio-group v-model="item.leaveType" size="small">
                <el-radio
                  v-for="(type, typeIndex) in leaveTypeList"
                  :key="typeIndex"
                  :label="type.id"
                  >{{ type.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>

            <el-form-item
              :label="'请假时间'"
              :prop="'leaveItems.' + index + '.dateRange'"
              :rules="leaveRules.leaveStartDate"
            >
              <el-date-picker
                v-model="item.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy/MM/dd"
                format="yyyy/MM/dd"
                :picker-options="pickerOptions"
                @change="(val) => leaveDateChange(val, index)"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              :label="'请假时长'"
              :prop="'leaveItems.' + index + '.leaveDuration'"
            >
              {{ item.leaveDuration }}天（系统自动计算）
            </el-form-item>

            <el-form-item
              :label="'请假原因'"
              :prop="'leaveItems.' + index + '.leaveCause'"
              :rules="leaveRules.leaveCause"
            >
              <el-input
                type="textarea"
                :rows="3"
                v-model="item.leaveCause"
                placeholder="请输入请假原因"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item
              :label="'请假条'"
              :prop="'leaveItems.' + index + '.leavePicture'"
              :rules="leaveRules.leavePicture"
            >
              <image-upload
                :limit="1"
                :fileSize="10"
                v-model="item.leavePicture"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="leaveSubmit">确 定</el-button>
        <el-button @click="leaveShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="考勤调整记录"
      :visible.sync="logShow"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerLeaveList />
      <div slot="footer" class="dialog-footer">
        <el-button @click="logShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="销假"
      :visible.sync="closeLevelShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerLeaveClose
        v-if="closeLevelShow"
        :register-id="registerId"
        :register-start-date="registerStartDate"
        :register-end-date="registerEndDate"
        :close-leave="closeLeave"
        @close="closeLevelClose"
      />
    </el-dialog>

    <el-dialog
      title="查看详情"
      :visible.sync="detailShow"
      width="1050px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerLeaveDetail
        v-if="detailShow"
        :register-id="registerId"
        @openLeaveClose="closeLevelShow = true"
        @close="detailShow = false"
      />
    </el-dialog>
    <el-dialog
      title="报名详情"
      :visible.sync="detailShowInfo"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShowInfo"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShowInfo = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 学员选择弹框 -->
    <el-dialog
      title="选择学员"
      :visible.sync="studentDialogVisible"
      width="60%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="studentQueryParams"
        :inline="true"
        class="demo-form-inline"
      >
        <el-form-item label="学员姓名">
          <el-input
            v-model="studentQueryParams.userName"
            placeholder="输入姓名筛选"
            clearable
            @keyup.enter.native="filterStudents"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterStudents">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="studentDataList"
        highlight-current-row
        @current-change="selectStudent"
        height="400"
        v-loading="studentLoading"
      >
        <el-table-column property="userName" label="姓名" />
        <el-table-column property="registerDeptName" label="进修科目" />
        <el-table-column property="jobNumber" label="工号" />
      </el-table>

      <div v-if="studentDataList.length < studentTotal" class="load-more">
        <el-button type="text" @click="loadMoreStudents">加载更多</el-button>
      </div>

      <div v-else-if="studentTotal > 0" class="no-more">没有更多数据了</div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="studentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmStudentSelection"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveLeaveRegisterBase,
} from "@/api/business/registerBase";
import { listAllRegisterDept } from "@/api/business/registerDept";
import {
  delRegisterInfo,
  listAllRegisterInfo,
  listRegisterInfo,
} from "@/api/business/registerInfo";
import { setupBatchData } from "@/utils/batchUtils";
import { getDayDiff } from "@/utils/dateUtils";

import { listAllRegisterType } from "@/api/business/registerType";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";
import registerLeaveClose from "./components/registerLeaveClose";
import registerLeaveDetail from "./components/registerLeaveDetail";
import registerLeaveList from "./components/registerLeaveList";

export default {
  name: "leave",
  components: {
    registerLeaveList,
    registerLeaveClose,
    registerLeaveDetail,
    registerInfoDetailInfo,
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        leaveStatus: null,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerInfoList: [],
      batchDateList: [],

      registerBatchList: consts.registerBatchList,
      registerBaseVo: {},
      // 页面显示
      showType: 1,
      // 考勤状态调整
      leaveShow: false,
      leaveForm: {},
      leaveStatusList: consts.leaveStatusList,
      leaveTypeList: consts.leaveTypeList,
      leaveDateRange: [],
      leaveRules: {
        registerId: [
          { required: true, message: "学员不能为空", trigger: "blur" },
        ],
        leaveStatus: [
          { required: true, message: "请假状态不能为空", trigger: "change" },
        ],
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "change" },
        ],
        leaveStartDate: [
          { required: true, message: "请假时间不能为空", trigger: "blur" },
        ],
        leaveEndDate: [
          { required: true, message: "请假时间不能为空", trigger: "blur" },
        ],
        leaveDuration: [
          { required: true, message: "请假时长不能为空", trigger: "blur" },
        ],
        leaveCause: [
          { required: true, message: "请假原因不能为空", trigger: "blur" },
          { max: 100, message: "请假原因不能超过100字", trigger: "blur" },
        ],
        leavePicture: [
          { required: true, message: "请假条不能为空", trigger: "blur" },
        ],
      },
      registerId: null,
      // 考勤调整记录
      logShow: false,
      // 一键销假
      closeLevelShow: false,
      // 查看详情
      detailShow: false,
      tagIndex: 0,
      registerInfo: {
        id: null,
      },
      detailShowInfo: false, // 报名详情
      registerStartDate: null, // 进修开始时间
      registerEndDate: null, // 进修结束时间
      closeLeave: null, // 销假总长
      pickerOptions: {
        disabledDate: (time) => {
          const startDate = new Date(this.leaveForm.registerStartDate);
          const endDate = new Date(this.leaveForm.registerEndDate);
          return (
            time.getTime() < startDate.getTime() ||
            time.getTime() > endDate.getTime()
          );
        },
      },
      // 学员选择弹框相关
      studentDialogVisible: false,
      studentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        sureStatus: 2,
        leaveStatus: null,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
      },
      studentDataList: [],
      studentTotal: 0,
      selectedStudent: null,
      studentLoading: false,
    };
  },
  async created() {
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
    // this.listAllRegisterInfo();
  },
  methods: {
    // 计算两个日期之间相差的天数(兼容Safari)
    getDayDiff(startDate, endDate) {
      return getDayDiff(startDate, endDate);
    },

    async getbatch() {
      await setupBatchData(this);
    },
    detailOpenInfo(row) {
      this.registerInfo.id = row.id;

      this.detailShowInfo = true;
    },

    // 请假弹框（选择学员）
    handleLeave() {
      this.studentDialogVisible = true;
      this.studentQueryParams = {
        sureStatus: 2,
        pageNum: 1,
        pageSize: 10,
      };
      this.studentDataList = [];
      this.studentTotal = 0;
      this.selectedStudent = null;
      this.getStudentList();
    },

    // 获取学员列表（用于弹框）
    getStudentList() {
      this.studentLoading = true;
      listRegisterInfo(this.studentQueryParams)
        .then((response) => {
          this.studentDataList = [...this.studentDataList, ...response.rows];
          this.studentTotal = response.total;
          this.studentLoading = false;
        })
        .catch(() => {
          this.studentLoading = false;
        });
    },

    // 学员筛选
    filterStudents() {
      this.studentQueryParams.pageNum = 1;
      this.studentDataList = [];
      this.getStudentList();
    },

    // 加载更多学员
    loadMoreStudents() {
      if (this.studentDataList.length >= this.studentTotal) return;

      this.studentQueryParams.pageNum += 1;
      this.getStudentList();
    },

    // 选择学员
    selectStudent(row) {
      this.selectedStudent = row;
    },

    // 确认选择学员
    confirmStudentSelection() {
      if (!this.selectedStudent) {
        this.$message.warning("请选择一个学员");
        return;
      }

      this.studentDialogVisible = false;
      this.leaveOpen(this.selectedStudent);
    },

    initData() {
      this.getCount();
      this.tagIndex = 2;
      this.queryParams.leaveStatus = 2;
      this.getList();
    },
    clickAll(index, value) {
      this.tagIndex = index;
      this.queryParams.leaveStatus = value;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    listAllRegisterInfo() {
      let params = {
        sureStatus: 2,
      };
      listAllRegisterInfo(params).then((response) => {
        this.registerInfoList = response.data;
      });
    },
    getCount() {
      queryByCountRegisterBase(this.queryParams).then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total =
            this.registerBaseVo.leaveStatus1 + this.registerBaseVo.leaveStatus2;
        }
      });
    },
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].total =
              this.dataList[i].leaveStatus1 + this.dataList[i].leaveStatus2;
          }
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        listRegisterInfo(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            let leaveDuration = 0;
            let closeStatus = false;
            for (
              let j = 0;
              j < this.dataList[i].registerLeaveVoList.length;
              j++
            ) {
              let leave = this.dataList[i].registerLeaveVoList[j];
              leaveDuration += leave.leaveDuration;
              if (!closeStatus && leave.effectiveStatus != 2) {
                closeStatus = true;
              }
            }
            this.dataList[i].leaveDuration = leaveDuration;
            this.dataList[i].closeStatus = closeStatus;
          }
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 请假
    leaveOpen(row) {
      this.leaveForm = {
        leaveStatus: 2,
        registerId: row.id ? row.id : null,
        userName: row.userName,
        totalLeaveDuration: row.leaveDuration || 0,
        leaveItems: [
          {
            leaveType: null,
            dateRange: [],
            leaveStartDate: null,
            leaveEndDate: null,
            leaveDuration: 0,
            leaveCause: null,
            leavePicture: null,
          },
        ],
        registerStartDate: row.registerNoticeVo
          ? row.registerNoticeVo.startDate
          : null,
        registerEndDate: row.registerNoticeVo
          ? row.registerNoticeVo.endDate
          : null,
      };
      this.leaveShow = true;
    },

    // 添加请假项
    addLeaveItem() {
      console.log("添加请假项");
      if (this.leaveForm.leaveItems.length < 5) {
        this.leaveForm.leaveItems.unshift({
          leaveType: null,
          dateRange: [],
          leaveStartDate: null,
          leaveEndDate: null,
          leaveDuration: 0,
          leaveCause: null,
          leavePicture: null,
        });
      }
    },

    // 移除请假项
    removeLeaveItem(index) {
      this.leaveForm.leaveItems.splice(index, 1);
      // 重新计算请假总时长
      this.updateTotalLeaveDuration();
    },

    // 请假日期变更
    leaveDateChange(val, index) {
      if (val && val.length > 0) {
        this.leaveForm.leaveItems[index].leaveStartDate = val[0];
        this.leaveForm.leaveItems[index].leaveEndDate = val[1];
        this.leaveForm.leaveItems[index].leaveDuration = this.dateDiffInDays([
          val[0],
          val[1],
        ]);
      } else {
        this.leaveForm.leaveItems[index].leaveStartDate = null;
        this.leaveForm.leaveItems[index].leaveEndDate = null;
        this.leaveForm.leaveItems[index].leaveDuration = 0;
      }
      // 重新计算请假总时长
      this.updateTotalLeaveDuration();
    },

    // 更新请假总时长
    updateTotalLeaveDuration() {
      let totalDuration = 0;
      this.leaveForm.leaveItems.forEach((item) => {
        totalDuration += item.leaveDuration || 0;
      });
      this.leaveForm.totalLeaveDuration = totalDuration;
    },

    // 提交请假表单
    leaveSubmit() {
      this.$refs.leaveForm.validate((valid) => {
        if (valid) {
          // 处理请假数据
          let leaveData = {
            leaveItems: this.leaveForm.leaveItems.map((item) => {
              return {
                registerId: this.leaveForm.registerId,
                leaveStatus: 2,
                leaveType: item.leaveType,
                leaveStartDate: item.leaveStartDate,
                leaveEndDate: item.leaveEndDate,
                leaveDuration: item.leaveDuration,
                leaveCause: item.leaveCause,
                leavePicture: item.leavePicture,
              };
            }),
          };

          // 调用保存接口，这里需要修改后端接口以支持多条请假记录
          saveLeaveRegisterBase(leaveData).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.leaveShow = false;
            this.getList();
          });
        }
      });
    },
    // 考勤调整记录
    logOpen() {
      this.logShow = true;
    },
    // 销假
    closeLevelOpen(row) {
      this.registerId = row.id;
      this.registerStartDate = row.registerNoticeVo
        ? row.registerNoticeVo.startDate
        : null;
      this.registerEndDate = row.registerNoticeVo
        ? row.registerNoticeVo.endDate
        : null;
      this.closeLeave = row.leaveStat.closeDays;
      this.closeLevelShow = true;
    },
    closeLevelClose() {
      this.initData();
      this.closeLevelShow = false;
    },
    // 查看详情
    detailOpen(row) {
      this.registerId = row.id;
      this.detailShow = true;
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    // 删除
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报名信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterInfo(ids);
        })
        .then(() => {
          this.initData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 切换视图
    showTypeChange() {
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      const selectedId = this.dataList[index].id;
      if (checked) {
        if (!this.ids.includes(selectedId)) {
          this.ids.push(selectedId);
        }
      } else {
        this.ids = this.ids.filter((id) => id !== selectedId);
      }
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    // 计算日期差（天数）
    dateDiffInDays(dateRange) {
      if (!dateRange || dateRange.length < 2) {
        return 0;
      }
      const startDate = new Date(dateRange[0]);
      const endDate = new Date(dateRange[1]);
      // 计算两个日期之间的毫秒差
      const diffTime = Math.abs(endDate - startDate);
      // 转换为天数（包含起始日期和结束日期）
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
      return diffDays;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

.user-name {
  display: flex;
  align-items: center;
}

.box-container {
  padding: 0;
  padding-left: 20px;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  /* 控制列之间的间距 */
  background: #eeeff4;
  padding: 20px 0;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

.custom-table {
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #d8d8d8;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 4);
      // font-weight: bolder;

      .desc {
        font-size: 12px;
        color: #888;
        margin-top: 10px;
        font-weight: normal;
      }
    }
  }

  .custom-dept:hover {
    border: 1px solid red;
  }

  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // border: 1px solid rgb(232, 232, 232);
    // padding: 10px;
    // text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    .info {
      display: flex;
      justify-content: space-between;
      color: #606266;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        font-size: 14px;
        width: 375px;
        line-height: 20px;
        flex: 1;
      }
    }

    .col {
      .desc {
        color: #666666;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    .col:nth-child(1) {
      width: calc(100% - 600px);
      text-align: left;
    }

    .col:nth-child(2) {
      width: 200px;
    }

    .col:nth-child(3) {
      width: 200px;
    }

    .col:nth-child(4) {
      width: 200px;
    }

    .col:nth-child(5) {
      width: 200px;
    }
  }
}
</style>

<style lang="scss" scoped>
.load-more {
  text-align: center;
  padding: 10px 0;
  color: #409eff;
  cursor: pointer;
}

.no-more {
  text-align: center;
  padding: 10px 0;
  color: #999;
}
</style>
